<template>
  <view class="add-student-page">
    <view class="page-header">
      <text class="page-title">添加学生</text>
    </view>
    <view class="form-container">
      <view class="form-item">
        <text class="item-label">学生姓名 <text class="required">*</text></text>
        <input
          class="item-input"
          v-model="studentForm.name"
          placeholder="请输入学生姓名"
          @change="checkNameUnique"
        />
        <text class="error-tip" v-if="nameError">{{ nameError }}</text>
      </view>
      <view class="form-item">
        <text class="item-label">出生日期 <text class="required">*</text></text>
        <uni-datetime-picker
          type="date"
          v-model="studentForm.birthday"
          placeholder="选择出生日期"
        />
      </view>
      <view class="form-item">
        <text class="item-label">性别 <text class="required">*</text></text>
        <uni-data-checkbox v-model="studentForm.gender" :localdata="config.genderList" />
      </view>
      <view class="form-item">
        <text class="item-label">联系人 <text class="required">*</text></text>
        <input class="item-input" v-model="studentForm.guardian" placeholder="请输入联系人姓名" />
      </view>
      <view class="form-item">
        <text class="item-label">联系电话 <text class="required">*</text></text>
        <input
          class="item-input"
          v-model="studentForm.guardianPhone"
          type="number"
          placeholder="请输入联系电话"
        />
      </view>
    </view>
    <view class="btn-container">
      <button class="submit-btn" :disabled="isSubmitting" @click="submitForm">保存</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { config } from '@/global'
import {
  addStudentAPI,
  checkStudentNameUniqueAPI,
  getStudentInfoAPI,
  updateStudentAPI,
} from '@/services/studentInfo.ts'
import type { StudentInfoItem } from '@/types/studentInfo'

// 判断是否为编辑模式
const isEditMode = ref(false)
// 学生ID
const studentId = ref()
// 学生表单数据
const studentForm = reactive<StudentInfoItem>({})

// 提交状态
const isSubmitting = ref(false)
// 姓名错误提示
const nameError = ref('')
// 姓名唯一性检查状态
const checkingName = ref(false)

// 获取路由参数
onLoad((options: any) => {
  // 首次加载数据
  studentId.value = Number(options.id)
  if (studentId.value) {
    isEditMode.value = true
    loadStudentInfo()
  }
})

// 加载学生信息
const loadStudentInfo = async () => {
  try {
    const res = await getStudentInfoAPI(studentId.value)
    Object.assign(studentForm, res.data)
  } catch (error) {
    console.error('加载学生信息失败:', error)
    uni.showToast({ title: '加载学生信息失败', icon: 'none' })
  }
}
// 检查姓名唯一性
const checkNameUnique = async () => {
  if (!studentForm.name?.trim()) {
    nameError.value = ''
    return
  }

  checkingName.value = true
  try {
    const res = await checkStudentNameUniqueAPI(studentForm)
    if (!res.data.isUnique) {
      nameError.value = '该学生姓名已存在'
    } else {
      nameError.value = ''
    }
  } catch (error) {
    console.error('检查姓名唯一性失败:', error)
    nameError.value = '检查姓名唯一性失败，请重试'
  } finally {
    checkingName.value = false
  }
}

// 提交表单
const submitForm = async () => {
  // 简单验证
  if (!studentForm.name?.trim()) {
    uni.showToast({ title: '请输入学生姓名', icon: 'none' })
    return
  }

  if (nameError.value) {
    uni.showToast({ title: nameError.value, icon: 'none' })
    return
  }

  if (!studentForm.birthday) {
    uni.showToast({ title: '请选择出生日期', icon: 'none' })
    return
  }

  if (!studentForm.gender) {
    uni.showToast({ title: '请选择性别', icon: 'none' })
    return
  }

  if (!studentForm.guardian) {
    uni.showToast({ title: '请输入联系人姓名', icon: 'none' })
    return
  }

  if (!studentForm.guardianPhone) {
    uni.showToast({ title: '请输入联系电话', icon: 'none' })
    return
  }

  isSubmitting.value = true
  try {
    if (isEditMode.value) {
      // 编辑模式
      await updateStudentAPI(studentForm)
      uni.showToast({ title: '更新成功' })
    } else {
      // 添加模式
      await addStudentAPI(studentForm)
      uni.showToast({ title: '添加成功' })
    }
    // 触发列表刷新
    uni.$emit('refreshStudentList')
    // 返回上一页
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  } catch (error) {
    console.error(isEditMode.value ? '更新学生失败:' : '添加学生失败:', error)
    uni.showToast({
      title: isEditMode.value ? '更新失败，请重试' : '添加失败，请重试',
      icon: 'none',
    })
  } finally {
    isSubmitting.value = false
  }
}
</script>

<style scoped lang="scss">
.add-student-page {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
}

.page-header {
  padding: 30rpx 0;
  text-align: center;
  border-bottom: 1rpx solid #eee;
  margin-bottom: 30rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.form-container {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.item-label {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.required {
  color: #f56c6c;
}

.item-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  font-size: 28rpx;
}

.error-tip {
  font-size: 24rpx;
  color: #f56c6c;
  margin-top: 6rpx;
  display: block;
}

.picker-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  padding: 0 20rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  line-height: 80rpx;
  color: #999;
}

.radio-group {
  display: flex;
  padding: 20rpx 0;
}

.radio-item {
  display: flex;
  align-items: center;
  margin-right: 40rpx;
  font-size: 28rpx;
}

.image-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;
}

.preview-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 50%;
  margin-bottom: 20rpx;
}

.upload-btn {
  background-color: #f5f7fa;
  color: #606266;
  font-size: 28rpx;
  padding: 0 40rpx;
}

.btn-container {
  padding: 0 20rpx;
}

.submit-btn {
  background-color: $student-primary-color;
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;
  height: 90rpx;
  line-height: 90rpx;
  width: 100%;
}
</style>
